package com.example.frn.interceptor;

import com.example.frn.util.JwtUtil;
import com.example.frn.vo.R;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/**
 * 权限验证的拦截器，在请求进入到控制器之前先判断是否具备访问权限
 */

@Component

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 从请求对象中获取令牌
//        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiLnlKjmiLfnmbvlvZXorqTor4EiLCJpc3MiOiJMaVllIiwidGVsIjoiMTMwMDk4NDExMTEiLCJleHAiOjE3MjM0MzEwNzcsImlhdCI6MTcyMzQyOTI3NywidXNlcklkIjoiMTAxIiwianRpIjoiZmFiZGFmNmYtYmFiMS00MGQ4LThhNDQtNjY1ZmZhODJlM2Y5IiwidXNlcm5hbWUiOiJhZG1pbiJ9.28uERSwTKId1SeKB0h7Lf2WyqaI23wWFCPpRvdnK_0U";
        String token = request.getHeader("authorization");
        // 对这个令牌进行核验
        try {
            Map<String, String> resultMap = JwtUtil.verify(token);
            // 如果上一步的核验过程通过了，说明token合法
            return true;// 返回真，对此次请求放行
        } catch (Exception ex) {
            // 反之，如果核验的过程中发生了异常，说明token非法（null、过期、伪造）
            ex.printStackTrace();//在控制台打印异常信息
            response.setContentType("text/json");
            response.setCharacterEncoding("utf-8");
            R result = new R(401, "token核验错误，您没有访问权限~", null);
            response.setStatus(401);// 设置响应状态码为 401
            ObjectMapper objectMapper = new ObjectMapper();
            // 将result对象转换成JSON格式，响应给客户端
            objectMapper.writeValue(response.getWriter(), result);
//            response.getWriter().write("token核验错误，您没有访问权限~");
            return false; // 返回假，拦截请求
        }
    }

}
